package com.aischool.service;

import java.io.File;
import java.util.List;

import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;

public class AiCourseClassService {

	public List<Record> getClass(int course_id){
		return Db.find("SELECT * FROM ai_course_class WHERE course_id = ? ORDER BY parent_id, class_sort, class_id", course_id);
	}
	
	public Record getOne(int class_id) {
		return Db.findFirst("SELECT * FROM ai_course_class WHERE class_id = ?", class_id);
	}
	
	public List<Record> getChild(int parent_id) {
		return Db.find("SELECT * FROM ai_course_class WHERE parent_id = ?", parent_id);
	}
	
	public int delClass(int class_id, String webroot) {
		int ir = 0;
		Record rd = getOne(class_id);
		if (rd != null) {
			if (StrKit.notBlank(rd.getStr("file_url"))) {
				delFile(rd.getStr("file_url"), webroot);
			}
			ir = Db.delete("DELETE FROM ai_course_class WHERE class_id = ?", class_id);
			if(ir>0 && rd.getInt("class_typeid") == 1) {
				List<Record> listrd = getChild(class_id);
				for(int i=0;i<listrd.size();i++) {
					if (StrKit.notBlank(listrd.get(i).getStr("file_url"))) {
						delFile(listrd.get(i).getStr("file_url"), webroot);
					}
				}
				ir += Db.delete("DELETE FROM ai_course_class WHERE parent_id = ?", class_id);
			}
		}
		return ir;
	}
	
	@SuppressWarnings("unused")
	private void delFile(String filepath, String webroot) {
		try {
			File file1 = new File(webroot + filepath);
			if (file1.exists()) {
				file1.delete();
			}
		}catch(Exception ex) {}
	}
}
